package com.greenyoung.pwiki.elasticsearch.index.event;

import com.alibaba.fastjson.JSON;
import com.greenyoung.pwiki.common.consts.ConstElIndex;
import com.greenyoung.pwiki.common.consts.ConstMq;
import com.greenyoung.pwiki.elasticsearch.index.entity.ElIndexRecordEntity;
import com.greenyoung.pwiki.elasticsearch.index.entity.Markdown;
import com.greenyoung.pwiki.elasticsearch.index.entity.OssFileEntity;
import com.greenyoung.pwiki.elasticsearch.index.service.ElIndexRecordService;
import com.greenyoung.pwiki.elasticsearch.index.utils.IndexUtils;
import com.greenyoung.pwiki.elasticsearch.index.utils.PipelineUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * 接送到消息队列中的创建索引请求
 */
@Component
public class DoIndexReceiver {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ElIndexRecordService elIndexRecordService;

    /**
     * 收到消息队列中的文件id，向数据库发送请求，获取文件url以及文件类型，并根据url进行文件索引
     *
     * @param msg 收到的数据应是个json
     */
    @RabbitListener(queues = ConstMq.ELASTICSEARCH_INDEX_QUEUE)
    public void process(String msg) throws IOException {
        logger.info("[*] 索引接收器收到消息队列发来的消息：" + msg);
        OssFileEntity fileEntity = JSON.parseObject(msg, OssFileEntity.class);
        switch (fileEntity.getType()) {
            case "md":
                logger.info("[*] 开始索引markdown文件：" + fileEntity.getUrl());
                IndexUtils.IndexMarkdownWithPipeline(msg);

                ElIndexRecordEntity elIndexRecordEntity = new ElIndexRecordEntity();
                elIndexRecordEntity.setId(fileEntity.getId());
                elIndexRecordEntity.setStatus(1);
                elIndexRecordEntity.setUpdateTime(new Date());
                elIndexRecordService.updateById(elIndexRecordEntity);
                logger.info("[+] 索引记录已更新：" + elIndexRecordEntity);

                break;
            case "pdf":
                logger.info("[*] 开始索引pdf文件：" + fileEntity.getUrl());
                break;
            default:
                break;
        }
    }

}
